
<script src="../../service/caseService.js"></script>
<template>
  <div>
    <Row justify="center">
      <Col span="12"align="left" >
      <Select v-model="social"  @on-change="getAnnouncementList" style="width:200px;" align="left">
          <Option  value="3" >全部</Option>
          <Option  value="1" >有效</Option>
          <Option  value="0" >无效</Option> 
          <Option  value="2" >失效</Option> 
      </Select>
      </Col>
      <Col span="12" align="right">
      <Button type="info" @click="modalAdd = true">添加公告</Button>
      </Col>
    </Row>
    <br>
    <Table :loading="Tableloading" border :columns="columns" :data="data6"></Table>
    <br>
    <Page :total="count" placement="top" :page-size-opts="opts" size="small" :page-size="size" show-total show-elevator show-sizer   @on-change="changePage" @on-page-size-change="changeSize"></Page>
    <Modal :styles="{top: '20px'}" v-model="modalAdd" title="添加公告" @on-ok="ok" :loading="loading" @on-cancel="cancel" width="600">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <FormItem label="公告标题" prop="title">
          <Input v-model="formValidate.title" placeholder="请输入公告的标题"></Input>
        </FormItem>
        <FormItem label="开始时间">
           <DatePicker v-model="startLine"  type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请输入开始时间" ></DatePicker>
        </FormItem>
        <FormItem label="结束时间">
           <DatePicker v-model="endLine"  type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请输入结束时间" ></DatePicker>
        </FormItem>
        <FormItem label="公告类型" prop="gender">
          <RadioGroup v-model="formValidate.gender">
            <Radio label="lamp">跑马灯</Radio>
            <Radio label="nolamp">普通</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="公告内容" prop="desc">
          <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入公告内容"></Input>
        </FormItem>
        <FormItem label="可看群组" >
          <Row>
            <Col span="7">
                <Tree show-checkbox :data="treedata"  multiple ref="tree" @on-check-change="getAllSelect"></Tree>
            </Col>
            <!-- <Col span="4">
                <Button type="info" @click="getGroup">
                  <Icon type="arrow-right-c" size="20" ></Icon>
                </Button>
            </Col> -->
            <Col span="17">
                <Table :loading="TablePersonloading" :height="manTableHeight" style="min-height:120px;" border ref="selection" :columns="columns4" :data="data1" @on-selection-change="select"></Table>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import announcement from "service/announcement.js";
import marquee from 'components/marquee/marquee.vue';
import {
  mapGetters
} from 'vuex'
export default {
  name: "announcement",
  components: {
      marquee
  },
  data() {
    return {
     page: 0,
      size: 10,
      count:0,
      opts:[10],
      modalAdd: false,
      loading: true,
      social: "3",
      manTableHeight:"180",
      ULHeight:"",
      grpupId:[],
      groupManageId:[],
      Tableloading:true,
      TablePersonloading:false,
      startLine:"",
      endLine:"",
      columns: [
        {
          title: "起始时间",
          key: "startTime",
          align: "center"
        },
        {
          title: "终止时间",
          key: "endTime",
          align: "center"
        },
        {
          title: "标题",
          key: "title",
          align: "center"
        },
        {
          title: "公告状态",
          key: "status",
          align: "center",
          render: (h, params) => {
            return h("div", [h("div", {}, this.changeStatus(params.row))]);
          }
        },
        {
          title: "公告类型",
          key: "noticeType",
          align: "center",
          render: (h, params) => {
            return h("div", [h("div", {}, this.changeNoticeType(params.row))]);
          }
        },

        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.show(params.row);
                    }
                  }
                },
                "详情"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                    disabled: this.pauseStatus(params.row)
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.pause(params.row);
                    }
                  }
                },
                "暂停"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",

                    size: "small",

                    disabled: this.startStatus(params.row)
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.start(params.row);
                    }
                  }
                },
                "启动"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",

                    size: "small",

                    disabled: this.removeStatus(params.row)
                  },

                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],

      formValidate: {
        title: "",
        gender: "",
        desc: ""
      },
      ruleValidate: {
        title: [
          {
            required: true,
            message: "公告标题不能为空",
            trigger: "blur"
          },
          {
            type: "string",
            max: 20,
            message: "不能多与20字符",
            trigger: "blur"
          }

        ],
        gender: [
          {
            required: true,
            message: "请选择公告类型",
            trigger: "change"
          }
        ],
        desc: [
          {
            required: true,
            message: "请输入公告内容",
            trigger: "blur"
          },
          {
            type: "string",
            min: 1,
            message: "不能少于1个字符",
            trigger: "blur"
          },
          {
            type: "string",
            max: 200,
            message: "不能多与200字符",
            trigger: "blur"
          }
        ]
      },

      treedata: [],
      columns4: [
          {
              type: 'selection',
              width: "60",
              align: 'center'
          },
          {
              title: '姓名',
              key: 'userName',
              align:'center'
          }
      ],
      data1: [],
      data6: [ ]
    };
  },
  computed: {
    ...mapGetters({
      loginUserInfo: 'loginUserInfo',
    }),
  },
  watch: {
      loginUserInfo(newVal, oldVal) {
          this.getAnnouncementList()
      }
  },
  methods: {
    // 显示详情
    show(row) {
      console.log(row)
      this.$Modal.info({
        title: "公告详情",
        content: `<span class='info_title'>标题：</span>${row.title}<br><br><span class='info_title'>内容：</span>${row
          .desp}<br><br><span class='info_title'>有效期：</span>${row.startTime}&nbsp;至&nbsp;${row.endTime}`
      });
    },

    // 暂停状态判断

    pauseStatus(row) {
      if (row.status === "1") {
        return false;
      } else {
        return true;
      }
    },

    // 启动状态判断

    startStatus(row) {
      if (
        row.status === "0"
      ) {
        return false;
      } else {
        return true;
      }
    },

    // 删除按钮启用禁用判断

    removeStatus(row) {
      if (
        row.status === "0" ||
        row.status === "2"
      ) {
        return false;
      } else {
        return true;
      }
    },

    // 暂停事件
    pause(row) {
      this.changeAnnouncementStatus(row.id,"0");
    },

    // 启用事件
    start(row) {
      this.changeAnnouncementStatus(row.id,"1");
    },

    // 删除事件
    remove(row) {
      this.deleteAnnouncement(row.id)
    },
    changeLoading() {
      this.loading = false;
      this.$nextTick(() => {
        this.loading = true;
      });
    },

    // 添加公告
    ok() {
      this.$refs["formValidate"].validate(valid => {
        if (valid) {
          if(this.startLine && this.endLine ){
             //时间比较
             if(this.getTimestamp(this.startLine)<Date.parse(new Date())){
                this.$Message.warning("开始时间不能小于当前时间");
                return this.changeLoading();
                return false
             }
             if(this.getTimestamp(this.startLine)<this.getTimestamp(this.endLine)){
                if(this.grpupId.length){
                  this.addAnnouncement();
                }else{
                  this.$Message.warning("请选择可看人组");
                  return this.changeLoading();
                }
             }else{
               this.$Message.warning("开始时间不能大于结束时间");
               return this.changeLoading();
             }
          }else{
            this.$Message.warning("请数入开始时间或结束时间");
            return this.changeLoading();
          }
        } else {
          return this.changeLoading();
        }
      });
    },
    // 取消添加
    cancel() {
      this.$refs["formValidate"].resetFields();
    },
    changeStatus(row) {
      if (row.status === "1") {
        return "有效";
      } else if (row.status === "0") {
        return "无效";
      } else if (row.status === "2") {
        return "失效";
      }
    },
    changeNoticeType(row) {
      if (row.noticeType === "2") {
        return "跑马灯";
      } else{
        return "普通公告";
      }
    },
    changePage(response) {
      var _that = this;
     _that.page = response-1;
     _that.getAnnouncementList();
    },
    changeSize(response) {
      var _that = this;
      _that.size = response;
      _that.getAnnouncementList();
    },
    async getAnnouncementList() {
        if(!this.loginUserInfo.userId){
          return false;
        }
        let search_data={
           pageNumber:this.page,
           pageSize:this.size
        };
        let userKey = this.loginUserInfo.userId
        let vm = this;
        let status_array=[];
        if(vm.social==="3"){
           status_array="";
        }else{
          status_array.push(vm.social);
        }
        let jsondata = await announcement.list(search_data,userKey,status_array);
        vm.Tableloading=false;
        vm.count=jsondata.totalElements
        vm.data6=jsondata.content;
    },
    async addAnnouncement() {
        let vm = this;
        let noticeType = 1;
        if(this.formValidate.gender==="lamp"){
            noticeType = 2;
        }
        let addData={
            title: this.formValidate.title,
            desp: this.formValidate.desc,
            startTime: this.changeDateType(this.startLine).date+' '+this.changeDateType(this.startLine).time,
            endTime: this.changeDateType(this.endLine).date+' '+this.changeDateType(this.endLine).time,
            noticeType: noticeType,
            readers: this.grpupId,
            status: '1'
        };
        let jsondata = await announcement.add(addData);
        if(jsondata.id){
        vm.changeLoading();
        vm.modalAdd = false;
        vm.$Message.success("添加成功");
        vm.$refs["formValidate"].resetFields();
        this.getAnnouncementList();
        }else{
          this.$Message.error("添加失败");
          return this.changeLoading();
        }

    },
    async deleteAnnouncement(id) {
        let vm = this;
        let jsondata = await announcement.delete(id);
        this.getAnnouncementList();
    },
    async changeAnnouncementStatus(id,status) {
        let vm = this;
        let jsondata = await announcement.changeStatus(id,status);
        if(jsondata.id){
          if(status==="1"){
             vm.$Message.info("已开启");
          }else{
             vm.$Message.info("已暂停");
          }
           vm.getAnnouncementList();
          //  跑马灯
          
        }else{
          if(status==="1"){
             vm.$Message.error("开启失败");
          }else{
             vm.$Message.error("暂停失败");
          }
        }
    },
    // 查询结构图
    async getOrganizationList() {
        let vm = this;
        let jsondata = await announcement.getOrganizationList();
        vm.treedata = getTree(jsondata);
        function getTree(tree = []) {
            let arr = [];
            if (!!tree && tree.length !== 0) {
                tree.forEach(item => {
                    let obj = {};
                    obj.title = item.text;
                    obj.attr = item.id; // 其他你想要添加的属性
                    obj.expand = false;
                    obj.children = getTree(item.children); // 递归调用
                    arr.push(obj);
                });
            }
            return arr;
        }
    },
    // 查询结构图下的人
    async getOrganizationPerson(id_list) {
        let vm = this;
        let idStr="";
        id_list.forEach(function(ele,index){
            var ico_ = index ? ",":""
            idStr=idStr+ico_+ele
        });
        let jsondata = await announcement.getOrganizationPerson({ orgIdList: idStr});
           vm.data1 =  jsondata ;
           vm.TablePersonloading=false;
    },
    select(row){
    var vm= this;
    vm.grpupId=[];
     row.forEach(function(ele){
        vm.grpupId.push(ele.userId)
     })
    },
    // getGroup:function(){
    //  let SelectedNode= this.$refs.tree.getSelectedNodes();
    //  let vm = this;
    //  vm.groupManageId=[];
    //  SelectedNode.forEach(function(item){
    //   vm.groupManageId.push(item.attr)
    //  })
    //  if(vm.groupManageId.length){
    //     vm.getOrganizationPerson(vm.groupManageId)
    //  }else{
    //     this.$Message.warning('请先选择组织架构');

    //  }
    // },
    getAllSelect(response){
        this.TablePersonloading=true;
        let SelectedNode= response;
        let vm = this;
        vm.groupManageId=[];
        SelectedNode.forEach(function(item){
          vm.groupManageId.push(item.attr)
        })
        vm.getOrganizationPerson(vm.groupManageId)
    },
    changeDateType(date){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second = date.getSeconds();
      second = second < 10 ? ('0' + second) : second;
      // y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
      return  {
        "date":y + '-' + m + '-' + d,
        "time":h+':'+minute+':'+second,
        "nowTime":y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
      }
    },
    getTimestamp(data){
        return Date.parse(data)
    }
  },
  mounted: function() {
    this.getAnnouncementList();
    this.getOrganizationList();
  }
};
</script>
<style>
.ivu-tree ul li {
  margin: 0;
}
.ivu-form-item-required .ivu-form-item-label:before {
  display: none;
}
.ivu-date-picker{
   width: 100%;
}
.info_title{
  font-weight: 600;
  color:#196AC1;
}
</style>

